import { ipcMain } from 'electron'
import * as cheerio from 'cheerio'
import ejs from 'ejs'
import fs from 'fs'
import prettier from 'prettier'

export const setupDomToDictHandlers = () => {
  ipcMain.handle('dom-to-dict', (_event, richText: any) => {
    return new Promise(async (resolve) => {
      const dictConfig = getDictConfig(richText)
      console.log(dictConfig)
      const dictRes = await renderDict(dictConfig)
      console.log(dictRes)
      resolve({ dictRes, totalLength: dictConfig.length + '' })
    })
  })
}

const renderDict = (dictConfig: any) => {
  return new Promise((resolve, reject) => {
    fs.readFile('./src/main/handlers/domToDict/dict.ejs', 'utf8', (err, template) => {
      if (err) {
        reject(err)
        console.error('Error reading template:', err)
        return
      }

      // 渲染模板，并传递变量
      const renderedTemplate = ejs.render(template, {
        dictConfig
      })

      const formattedTemplate = prettier.format(renderedTemplate, {
        parser: 'typescript',
        printWidth: 120,
        tabWidth: 4,
        useTabs: true
      })

      resolve(formattedTemplate)
    })
  })
}

const getDictConfig = (cleanHtml) => {
  const $ = cheerio.load(cleanHtml)
  const dictConfig: any = []

  // 查找所有 ul > li > span 结构
  $('ul li span').each((index, span) => {
    const text = $(span).text().trim()
    if (text) {
      dictConfig.push(text)
    }
  })

  return dictConfig
}
